package com.reggielcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggielcy.dto.DishDto;
import com.reggielcy.entity.Dish;
import com.reggielcy.entity.DishFlavor;
import com.reggielcy.mapper.DishMapper;
import com.reggielcy.service.DishFlavorService;
import com.reggielcy.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther teacher
 * @date 2024/3/28
 * @project reggie_take_out
 */

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;


    //同时保存
    @Transactional
    public void saveWithFlavors(DishDto dishDto){
        //保存菜品到dish表中
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long dishId = dishDto.getId();//菜品Id

        //再保存flavor数据前绑定dishId
        flavors.stream().map((flavor)->{
            flavor.setDishId(dishId);
            return flavor;
        }).collect(Collectors.toList());

        //批量保存flavors到flavors表中
        dishFlavorService.saveBatch(flavors);

    }
    @Transactional
    @Override
    public DishDto getByIdWithFlavors(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto=new DishDto();

        BeanUtils.copyProperties(dish,dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());

        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }
    @Transactional
    @Override
    public void updateWithFlavors(DishDto dishDto) {
        //先更新dish表中的数据
        this.updateById(dishDto);

        //根据Id先删除表中的口味数据
        Long dishId = dishDto.getId();

        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishId);

        dishFlavorService.remove(queryWrapper);

        //再插入口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        //再插入flavor数据前绑定dishId
        flavors.stream().map((flavor)->{
            flavor.setDishId(dishId);
            return flavor;
        }).collect(Collectors.toList());

        //批量保存
        dishFlavorService.saveBatch(flavors);




    }
}
